﻿using B.S.BasicData.Api.Read.Application.Command.RBAC;
using B.S.BasicData.Api.Read.DTO;
using B.S.BasicData.Domian.Entities.RBAC;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interface;
using MediatR;
using System;

namespace B.S.BasicData.Api.Read.Application.Handler.RBAC
{
    public class GetUserHandler : IRequestHandler<GetUserCommand, ApiPaging<GetUserDTO>>
    {
        private readonly IBaseRepository<UserModel> userRepo;
        private readonly IBaseRepository<RoleModel> roleRepo;

        public GetUserHandler(IBaseRepository<UserModel>userRepo,IBaseRepository<RoleModel>roleRepo)
        {
            this.userRepo = userRepo;
            this.roleRepo = roleRepo;
        }
        public Task<ApiPaging<GetUserDTO>> Handle(GetUserCommand request, CancellationToken cancellationToken)
        {
            var res=new ApiPaging<GetUserDTO>();
            var user = userRepo.GetAll().Where(x => x.IsDel == false);
            var role = roleRepo.GetAll().Where(x => x.IsDel == false);
            var linq = from a in user
                       join b in role on a.RoleId equals b.RoleId
                       select new GetUserDTO
                       {

                                    UserId      =a.UserId      ,
                                    RoleId      =a.RoleId      ,
                                    RoleName    =b.RoleName    ,
                                    UserName    =a.UserName    ,
                                    CreateTime  =a.CreateTime  ,
                                    CreatePeople=a.CreatePeople,
                                    UpdateTime  =a.UpdateTime  ,
                                    UpdatePeople=a.UpdatePeople,

                       };
            var totalcount = linq.Count();
            var totalpage = (int)Math.Ceiling(totalcount * 1.0 / request.PageSize);
            linq = linq.OrderByDescending(x => x.UserId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize);
            res.totalcount = totalcount;
            res.totalpage = totalpage;
            res.Message = "显示成功";
            res.Code = ApiEnum.Ok;
            res.Data = linq.ToList();
            return Task.FromResult(res);
        }
    }
}
